from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from python_residencia_rise.formularioApp.forms import FormulariosForm
from python_residencia_rise.formularioApp.models import Formulario
from django.utils.datetime_safe import datetime
from django.template.context import RequestContext
from python_residencia_rise.residenteApp.models import Residente
from python_residencia_rise.empresaApp.models import Empresa

def formulario(request):
    if request.method == 'POST':
        #if request.user.has_perm('formularioApp.'):
            form = FormulariosForm(request.POST)
            if form.is_valid():
                formulario = Formulario()
                formulario.dataInsercao = datetime.now()
                formulario.atividades = form.data['atividades']
                formulario.bibliografia = form.data['bibliografia']
                formulario.outrasInformacoes = form.data['outrasInformacoes']
                formulario.residente = Residente.objects.get(usuario = request.user)
                formulario.save()
                return HttpResponseRedirect('listar')
        
    else:
        form = FormulariosForm()
    return render_to_response('formulario.html', locals(), context_instance=RequestContext(request))

def listar_formularios(request):
    #SE FOR EMPRESA
    formularios = Formulario.objects.filter(residente__in = Residente.objects.filter(empresa = Empresa.objects.get(usuario = request.user)))
    #SE FOR RESIDENTE
    #formularios = Formulario.objects.filter(residente = Residente.objects.get(usuario = request.user))
    #SE NAO FOR DE NENHUM GRUPO
    #formularios = Formulario.objects.all()

    return render_to_response( 'listar_formularios.html', locals(), context_instance=RequestContext(request))
    